<?php
/**
 * Upgrade from 1.1.0 to 1.2.0
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: Upgrade_1_1_0.php 353 2010-01-31 15:14:50Z steen.rabol@gmail.com $
 */

Prado::using('Application.Common.Upgrade.PortalUpgrade');
class Upgrade_1_1_0 extends PortalUpgrade
{
	public function run()
	{
		parent::run();

		if(!$this->UpdateTables())
		{
			PortalUtil::fatalError("Upgrade faild: Update tables");
			return;
		}

		if(!$this->CreateNewTables())
		{
			PortalUtil::fatalError("Upgrade faild: Unable to create new tables");
			return;
		}

		if(!$this->DataUpgrade())
		{
			PortalUtil::fatalError("Upgrade faild: Data upgrade");
			return;
		}

		$this->UpdVersionNum('1.2.0');
	}

	public function UpdateTables()
	{
		// As we need to change a index, we need to do some work
		$singlesql	= sprintf("SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS WHERE table_schema = '%s' AND table_name = 'tblpages' AND index_name = 'nameidx'",$this->Application->Parameters['DbDatabase']);
		$cnt		= TPropertyValue::ensureInteger($this->DbConnection->createCommand($singlesql)->queryScalar());
		if($cnt !== 0)
		{
			$singlesql = "ALTER TABLE tblpages DROP INDEX nameidx";
			$this->DbConnection->createCommand($singlesql)->execute();
		}

		$sql = array
			(
				"ALTER TABLE `tblconfig` CHANGE `culture` `culture` VARCHAR( 25 ) NOT NULL DEFAULT 'en'",
				"ALTER TABLE `tblpages` CHANGE `metakeywords` `metakeywords` TEXT NULL",
				"ALTER TABLE `tblpages` CHANGE `metadescription` `metadescription` TEXT NULL",
				"ALTER TABLE `tblpages` ADD UNIQUE (`name` ,`fullpath`)",
				"ALTER TABLE `tblpages` CHANGE `culture` `culture` VARCHAR( 25 ) NOT NULL DEFAULT 'en'"
			);
		try
		{
			if(is_array($sql) && count($sql) != 0)
			{
				foreach($sql as $s)
				{
					try
					{
						$this->DbConnection->createCommand($s)->execute();
					}
					catch (TDbException $dbe)
					{
						PortalUtil::Log(sprintf("DB: %d %s, %s", $dbe->ErrorCode, $dbe->ErrorMessage,$s));
					}
				}
			}
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError("Update tables:<br>" . $e->getMessage());
		}
		return true;
	}

	public function CreateNewTables()
	{
		$sql = array();
		try
		{
			if(is_array($sql) && count($sql) != 0)
			{
				foreach($sql as $s)
				{
					$this->DbConnection->createCommand($s)->execute();
				}
			}
		}
		catch(Exception $e)
		{
			PortalUtil::fatalError("Create tables:<br>" . $e->getMessage());
			return false;
		}

		return true;
	}

	public function DataUpgrade()
	{
		return true;
	}
}
?>